//created by wzq 下拉列表组件
define(["jquery","iscroll-probe"],function($,IScroll) {
	
	function XYScroller(el, list, ops){
		var defaultOps = {scrollbars:true, fadeScrollbars:true, probeType:2, 
			pullDownLabel:"下拉刷新", pullDownMoveLabel:"松开刷新", pullDownLoadingLabel:"加载中....",
			pullUpLabel:"加载更多", pullUpMoveLabel:"释放加载", pullUpLoadingLabel:"加载中....", noMoreLoadLabel:"没有更多数据了"
		};
		ops = $.extend(defaultOps, ops);
		
		$(el).addClass("xy_scroller_wrapper");
		this.$pdElem = $(el).find(".xy_scroller_pulldown");
		this.$puElem = $(el).find(".xy_scroller_pullup");
		if(this.$pdElem.length > 0)
		{
			this.$pdElem.css("top",-this.$pdElem.height());
		}
		if(this.$puElem.length > 0)
		{
			this.$puElem.css("bottom",-this.$puElem.height());
		}
				
		this.iscroll = new IScroll(el, ops);
		this.iscroll.xyScroller = this;
		this.iscroll.on("scroll",this.onScrollMove);
		this.iscroll.on("scrollEnd",this.onScrollEnd);

		this.isNoMoreData(true);
	}
	
	XYScroller.prototype = {
		state:0,//0为普通状态；1为开始刷新列表；2为开始加载更多
		
		onScrollMove:function(){
			var scroller = this.xyScroller;
			if(scroller.state !== 0)return;
			var $pdElem = scroller.$pdElem, $puElem = scroller.$puElem;
			
			if($pdElem.length > 0 && this.y > $pdElem.height())
			{
				$pdElem.text(this.options.pullDownMoveLabel);
				scroller.state = 1;
			}
			else if(!scroller._isNoMoreData && $puElem.length > 0 && this.y < this.maxScrollY - $puElem.height())
			{
				$puElem.text(this.options.pullUpMoveLabel);
				scroller.state = 2;
			}
		},
		
		onScrollEnd:function(){
			var scroller = this.xyScroller,
			ops = this.options;
			if(scroller.state === 1)
			{
				scroller.$pdElem.text(ops.pullDownLabel);
				scroller.regenerate();
			}
			else if(scroller.state === 2)
			{
				scroller.$puElem.text(ops.pullUpLabel);
				ops.onLoadMore && ops.onLoadMore(this.wrapper);
			}
			scroller.state = 0;
		},
		
		regenerate:function(){
			var ops = this.iscroll.options;
			ops.onRefresh && ops.onRefresh();
		},

		refresh:function(){
			this.iscroll.refresh();
		},

		isNoMoreData:function(v){
			this._isNoMoreData = v;
			var ops = this.iscroll.options;
			this.$puElem.text(v ? ops.noMoreLoadLabel : ops.pullUpLabel);
		}
	}
	
	return XYScroller;
});